import { FC, ReactElement, useCallback, useEffect, useRef } from "react";
import { AbsolutePopup } from "./styled";
import { SubHead } from "../Text";
import styled from "styled-components";
import { animateScrollToTop } from "./utils";

interface IProps {
  active: boolean;
  year: number;
  selectYear: React.Dispatch<React.SetStateAction<number>>;
}

const startYear = new Date().getFullYear() - 50;

const YearSelected: FC<IProps> = ({
  active,
  year,
  selectYear,
}): ReactElement => {
  const yearRef = useRef<null | HTMLParagraphElement>(null);

  const scrollToYear = useCallback((element: HTMLParagraphElement) => {
    const { offsetTop, parentNode } = element;
    //@ts-ignore
    parentNode.scrollTop = offsetTop;
  }, []);

  useEffect(() => {
    if (yearRef.current && active) scrollToYear(yearRef.current);
  }, [active, scrollToYear]);
  // React.MouseEventHandler<HTMLDivElement>
  const handleSelectYear = useCallback(
    year =>
      ({ target: { offsetTop, parentNode } }: any) => {
        animateScrollToTop(offsetTop, parentNode)();
        selectYear(year);
      },
    [selectYear]
  );

  const renderItem = useCallback(
    (_, index) => {
      const y = startYear + index;
      const props = { key: index, children: y, onClick: handleSelectYear(y) };
      if (year === y)
        return (
          <ActiveYear
            style={{
              backgroundColor: "#51f",
            }}
            ref={yearRef}
            {...props}
          />
        );
      return <Year {...props} />;
    },
    [handleSelectYear, year]
  );

  return (
    <AbsolutePopup bottom={active ? 0 : "-100%"}>
      <div
        style={{
          display: "flex",
          flexWrap: "wrap",
          width: "100%",
          height: "100%",
          position: "relative",
          overflowY: "scroll",
        }}
      >
        {Array.from(Array(100), renderItem)}
      </div>
    </AbsolutePopup>
  );
};

export default YearSelected;

const Year = ({ ...props }: any) => (
  <SubHead
    style={{
      width: "25%",
      display: "flex",
      justifyContent: "center",
      alignItems: "center",
      padding: "0.2rem 0",
    }}
    {...props}
  />
);

const ActiveYear = styled(SubHead)`
  width: 25%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0.2rem 0;
  color: #fff;
`;
